package com.yoosora.plugins;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.mikuac.shiro.annotation.MessageHandler;
import com.mikuac.shiro.common.utils.MsgUtils;
import com.mikuac.shiro.common.utils.ShiroUtils;
import com.mikuac.shiro.core.Bot;
import com.mikuac.shiro.core.BotPlugin;
import com.mikuac.shiro.dto.event.message.WholeMessageEvent;
import com.yoosora.common.consts.ConstsS;
import com.yoosora.model.BangumiDTO;
import com.yoosora.model.BangumiDTO.Item;
import com.yoosora.utils.ApiConst;
import com.yoosora.utils.Collections;
import com.yoosora.utils.RegexConst;
import com.yoosora.utils.RequestUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.validation.constraints.NotNull;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Component
public class BangumiPlugin extends BotPlugin {
	Map<String, List<Item>> cache = Maps.newHashMap();
	
	@Scheduled(cron = "0 1 1 * * ?")
	public void cleanCache(){
		cache.clear();
		log.info(this.getClass().getSimpleName()+"缓存已清除");	
	}
	
	@MessageHandler(cmd = RegexConst.BANGUMI)
	public void bangumiMsg(@NotNull Bot bot, @NotNull WholeMessageEvent event){
		long groupId = event.getGroupId();
		int messageId = event.getMessageId();
		bot.sendMsg(event, MsgUtils.builder().text("番剧获取中...").reply(messageId).build(),false );
		String weekday = new SimpleDateFormat("EEEE").format(new Date());
		List<Item> items = null;
		if(null!=cache.get(weekday)&&Collections.isNotEmpty(cache.get(weekday))){
			items = cache.get(weekday);
		}else{
			String result = RequestUtils.builder().get().build(ApiConst.BANGUMI_API, null, null, null);
			List<BangumiDTO> bangumiDTOS = JSON.parseArray(result, BangumiDTO.class);
			BangumiDTO bangumiDTO = bangumiDTOS.stream().filter(o -> weekday.equals(o.getWeekday().getCn()))
					.findFirst().orElse(null);
			items = bangumiDTO.getItems();
			cache.put(weekday, items);
		}
		if(null!=items&&Collections.isNotEmpty(items)){
			List<String> msgList = items.stream().map(o -> 
					MsgUtils.builder()
							.text("番名(日文)：").text(o.getName()).text(ConstsS.RN)
							.text("番名(中文)：").text(Strings.isNotEmpty(o.getNameCn())?o.getNameCn():"(暂无)").text(ConstsS.RN)
							.text("播出日期：").text(o.getAirDate()).text(ConstsS.RN)
							.text("详情：").text(o.getUrl()).text(ConstsS.RN)
							.img(o.getImages().getLarge()).text(ConstsS.RN)
							.build()
			).collect(Collectors.toList());
			List<Map<String, Object>> list = ShiroUtils.generateForwardMsg(2315160273L, "博麗の巫女", msgList);
			bot.sendGroupForwardMsg(groupId,list);
		}else{
			bot.sendMsg(event, "获取番剧信息失败!", false);
		}
	}
}
